Skip to main content

Understanding the Flyweight Method Design Pattern in C#

 

The Flyweight Method design pattern is a structural pattern that helps reduce memory usage by sharing as much data as possible with other similar objects. It is particularly useful in scenarios where a large number of objects with similar properties are needed. The Flyweight Method  pattern achieves this by storing common data externally and referencing it, thereby minimizing memory consumption.

Understanding the Proxy Method Design Pattern in C#

Example Without the Flyweight Method Pattern

Let's consider a simple graphics application where we need to display a large number of circles with varying colors and coordinates. In a non-pattern approach, we might create a separate object for each circle, even if many circles share the same color.

using System;
using System.Collections.Generic;

namespace WithoutFlyweightMethodPattern
{
    // Circle class with color, x and y coordinates
    class Circle
    {
        public string Color { get; private set; }
        public int X { get; private set; }
        public int Y { get; private set; }

        public Circle(string color, int x, int y)
        {
            Color = color;
            X = x;
            Y = y;
        }

        public void Draw()
        {
            Console.WriteLine($"Drawing Circle [Color: {Color}, X: {X}, Y: {Y}]");
        }
    }

    // Client
    class Program
    {
        static void Main(string[] args)
        {
            List<Circle> circles = new List<Circle>();

            // Creating 1,000 circles with varying positions but only 5 colors
            string[] colors = { "Red", "Green", "Blue", "Yellow", "Black" };
            Random random = new Random();

            for (int i = 0; i < 1000; i++)
            {
                string color = colors[random.Next(colors.Length)];
                int x = random.Next(100);
                int y = random.Next(100);

                circles.Add(new Circle(color, x, y));
            }

            // Drawing all circles
            foreach (var circle in circles)
            {
                circle.Draw();
            }
        }
    }
}

Problems in the Non-Pattern Approach

  1. High Memory Usage: Creating a new object for each circle, even if many share the same color, results in a large amount of memory being used.
  2. Redundant Data: The same data (color) is stored multiple times, leading to redundancy and inefficiency.

How the Flyweight Method Pattern Solves These Problems

The Flyweight Method pattern minimizes memory usage by sharing common data (intrinsic state) among objects and storing unique data (extrinsic state) separately. In our example, the color is the intrinsic state, while the coordinates (x and y) are the extrinsic state.

Revisited Code with Flyweight Method Pattern

Let's implement the Flyweight Method pattern using a CircleFactory to manage shared instances of circles with the same color.

using System;
using System.Collections.Generic;

namespace FlyweightMethodPattern
{
    // Flyweight Interface
    interface ICircle
    {
        void Draw(int x, int y);
    }

    // Concrete Flyweight
    class Circle : ICircle
    {
        private string _color;

        public Circle(string color)
        {
            _color = color;
        }

        public void Draw(int x, int y)
        {
            Console.WriteLine($"Drawing Circle [Color: {_color}, X: {x}, Y: {y}]");
        }
    }

    // Flyweight Factory
    class CircleFactory
    {
        private static Dictionary<string, Circle> _circleMap = new Dictionary<string, Circle>();

        public static ICircle GetCircle(string color)
        {
            if (!_circleMap.ContainsKey(color))
            {
                _circleMap[color] = new Circle(color);
                Console.WriteLine($"Creating circle of color : {color}");
            }
            return _circleMap[color];
        }
    }

    // Client
    class Program
    {
        static void Main(string[] args)
        {
            // Creating 1,000 circles with varying positions but only 5 colors
            string[] colors = { "Red", "Green", "Blue", "Yellow", "Black" };
            Random random = new Random();

            for (int i = 0; i < 1000; i++)
            {
                string color = colors[random.Next(colors.Length)];
                int x = random.Next(100);
                int y = random.Next(100);

                ICircle circle = CircleFactory.GetCircle(color);
                circle.Draw(x, y);
            }
        }
    }
}

Benefits of the Flyweight Method Pattern

  1. Reduced Memory Usage: By sharing objects that have the same intrinsic state, the Flyweight Method pattern significantly reduces memory usage.
  2. Efficiency: The pattern avoids redundancy by storing shared data centrally.
  3. Scalability: It allows the creation of a large number of objects without a corresponding increase in memory usage.

Why Can't We Use Other Design Patterns Instead?

  • Singleton Pattern: The Singleton pattern ensures a single instance of a class, whereas the Flyweight Method pattern manages multiple instances with shared data.
  • Prototype Pattern: The Prototype pattern is about creating new objects by copying existing ones. It doesn't focus on sharing common data among objects.
  • Factory Method Pattern: While the Factory Method pattern is concerned with object creation, it doesn't inherently deal with sharing and minimizing memory usage like the Flyweight Method pattern.

Steps to Identify Use Cases for the Flyweight Method Pattern

  1. Large Number of Similar Objects: Identify situations where you need a large number of objects with similar properties.
  2. Memory Constraints: Use the Flyweight Method pattern when memory usage is a concern and you need to optimize resource usage.
  3. Shared Intrinsic State: Determine if there are common properties (intrinsic state) that can be shared among objects.
  4. Distinct Extrinsic State: Ensure that the unique properties (extrinsic state) can be managed separately from the shared state.

By applying the Flyweight Method design pattern, you can efficiently manage a large number of similar objects, reducing memory usage and improving system performance. This pattern is particularly valuable in scenarios where memory constraints are critical, such as in graphical applications or systems with limited resources.

Comments

Popular posts from this blog

Optional Parameters in C# — Writing Flexible and Clean Methods

Hello, .NET developers! 👋 How often have you created multiple method overloads just to handle slightly different cases? Maybe one method accepts two parameters, another three, and one more adds a flag for debugging? That’s a lot of code duplication for something that can be solved beautifully with optional parameters . Optional parameters in C# let you define default values for method arguments. When a caller doesn’t pass a value, the compiler automatically substitutes the default. This feature helps keep your APIs simple, readable, and maintainable. 🎥 Explore more on YouTube : DotNet Full Stack Dev Understanding Optional Parameters Optional parameters are defined by assigning default values in the method signature. When calling the method, you can omit those parameters if you’re okay with the defaults. Example public class Logger { public void Log(string message, string level = "INFO", bool writeToFile = false) ...

How Does My .NET Core Application Build Once and Run Everywhere?

One of the most powerful features of .NET Core is its cross-platform nature. Unlike the traditional .NET Framework, which was limited to Windows, .NET Core allows you to build your application once and run it on Windows , Linux , or macOS . This makes it an excellent choice for modern, scalable, and portable applications. In this blog, we’ll explore how .NET Core achieves this, the underlying architecture, and how you can leverage it to make your applications truly cross-platform. Key Features of .NET Core for Cross-Platform Development Platform Independence : .NET Core Runtime is available for multiple platforms (Windows, Linux, macOS). Applications can run seamlessly without platform-specific adjustments. Build Once, Run Anywhere : Compile your code once and deploy it on any OS with minimal effort. Self-Contained Deployment : .NET Core apps can include the runtime in the deployment package, making them independent of the host system's installed runtime. Standardized Libraries ...

.NET 10: Your Ultimate Guide to the Coolest New Features (with Real-World Goodies!)

 Hey .NET warriors! 🤓 Are you ready to explore the latest and greatest features that .NET 10 and C# 14 bring to the table? Whether you're a seasoned developer or just starting out, this guide will show you how .NET 10 makes your apps faster, safer, and more productive — with real-world examples to boot! So grab your coffee ☕️ and let’s dive into the awesome . 💪 1️⃣ JIT Compiler Superpowers — Lightning-Fast Apps .NET 10 is all about speed . The Just-In-Time (JIT) compiler has been turbocharged with: Stack Allocation for Small Arrays 🗂️ Think fewer heap allocations, less garbage collection, and blazing-fast performance . Better Code Layout 🔥 Hot code paths are now smarter, meaning faster method calls and fewer CPU cache misses. 💡 Why you care: Your APIs, desktop apps, and services now respond quicker — giving users a snappy experience . 2️⃣ Say Hello to C# 14 — More Power in Your Syntax .NET 10 ships with C# 14 , and it’s packed with developer goodies: Field-Bac...